package com.scs.application.modules.purchase.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.ReagentTeam;
import com.scs.application.modules.base.service.ReagentTeamService;
import com.scs.application.modules.purchase.dto.CloseOrderDTO;
import com.scs.application.modules.purchase.dto.PushOrderDTO;
import com.scs.application.modules.purchase.entity.Order;
import com.scs.application.modules.purchase.entity.OrderItem;
import com.scs.application.modules.purchase.service.OrderItemService;
import com.scs.application.modules.purchase.service.OrderService;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.thirdparty.dto.OrderQRCodeDTO;
import com.scs.application.modules.thirdparty.dto.OrderStatusDTO;
import com.scs.application.modules.thirdparty.service.MscmService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 采购订单 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/purchase/order")
@AllArgsConstructor
public class OrderController extends FlowController<OrderService, Order> {

    private final MscmService mscmService;
    @Autowired
    private ReagentTeamService reagentTeamService;
    @Autowired
    private OrderItemService orderItemService;

    /**
     * 同步至MSCM
     *
     * @return
     */
    @PostMapping("/pushOrder")
    public RestResult pushOrder(@RequestBody @Valid PushOrderDTO dto) {
        String fileName = service.pushOrder(dto.getIdList(), true);
        return RestResult.ok("订单推送成功", fileName);
    }

    @GetMapping("/printOrderQRCode")
    public RestResult printOrderQRCode(String orderId) {
        OrderQRCodeDTO orderQRCodeDTO= null;
        try {
            orderQRCodeDTO = service.printOrderQRCode(orderId);
        } catch (BusinessException e) {
            throw  e;
        } catch (Exception e) {
            throw new BusinessException("生成二维码失败,请联系管理员");
        }
        return  RestResult.ok("success",orderQRCodeDTO);
    }

    /**
     * 获取临采耗材的入库次数
     *
     * @return
     */
    @PostMapping("/getNum")
    public RestResult getNum(@RequestBody @Valid List<String> list){
        RestResult result = service.getNum(list);
        return result;
    }


    /**
     * 关闭订单
     * @param dto
     * @return
     */
    @PostMapping("/closeOrder")
    public RestResult closeOrder(@RequestBody @Valid CloseOrderDTO dto) {
        service.closeOrder(dto.getIdList(), dto.getReason(),dto.getFlagDeliveryClose(),dto.getUser());
        return RestResult.ok();
    }

    /**
     * 查询本周订单数量
     * @param
     * @return
     */
    @GetMapping("/findThisWeekPurchaseCount")
    public RestResult findThisWeekPurchaseCount() {
        Integer count = service.findThisWeekPurchaseCount();
        return RestResult.ok("查询成功",count);
    }

    @PostMapping("/orderStatus")
    public RestResult getOrderStatus(@RequestBody @Valid List<String> codes) {
        final String delivery = "4";
        final String finish = "4";
        List<OrderStatusDTO> orderDTOS = mscmService.pullOrderStatus(codes, null);
        Map<String,String> map = new HashMap<>();
        orderDTOS.stream().forEach(order -> {
            if(delivery.equals(order.getStatus().toString())) {
                map.put(order.getSourceKey(), "已发货是否确认关闭");
            }
            if(finish.equals(order.getIsClosed().toString())) {
                map.put(order.getSourceKey(), "已完成订单是否确认关闭");
            }
        });
        return RestResult.ok("ok",map);
    }

    private void fillEntity(Order entity) {
        if (StringUtils.isNotBlank(entity.getReagentTeamId())) {
            ReagentTeam reagentTeam =reagentTeamService.getById(entity.getReagentTeamId());
            if (reagentTeam != null) {
                entity.setReagentTeamName(reagentTeam.getName());
            }
        }

        entity.setCountDtl(orderItemService.count(Wrappers.<OrderItem>query().select("id").eq("order_id",entity.getId())));
    }



    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Order entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        if (StringUtils.isNotBlank(entity.getReagentTeamId())) {
            ReagentTeam reagentTeam =reagentTeamService.getById(entity.getReagentTeamId());
            if (reagentTeam != null) {
                entity.setReagentTeamName(reagentTeam.getName());
            }
        }

        fillEntity(entity);

        return RestResult.ok("获取数据成功", entity);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Order entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }
}
